package com.tjwx.service.impl;

import com.tjwx.dao.UserMapper;
import com.tjwx.model.JsonModel;
import com.tjwx.model.User;
import com.tjwx.service.UserService;
import com.tjwx.shiro.JWTToken;
import com.tjwx.shiro.JWTUtil;
import com.tjwx.util.MD5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Service("userService")
public class UserServiceImpl implements UserService {

    Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    UserMapper userMapper;


    @Override
    public JsonModel login(Map user, HttpServletResponse response) {

        try {
            JsonModel jsonModel;
            Map<String,Object> userinfo = userMapper.getUserInfo(user);
            if(null == userinfo){
                jsonModel = new JsonModel(false,"用户不存在","1111",null);
            }else{
                if(! userinfo.get("userpwd").equals(MD5Util.md5(user.get("password")+"",user.get("username")+""))){
                    jsonModel = new JsonModel(false,"密码不正确","1111",null);
                }else{
                    jsonModel = new JsonModel(true,"登录成功","0000",null);
                }
            }
            String token = JWTUtil.sign(userinfo.get("userid")+"", MD5Util.md5(user.get("password")+"",user.get("username")+""));
            JWTToken jwtToken = new JWTToken(token);
            Subject subject = SecurityUtils.getSubject();
            subject.login(jwtToken);
            userinfo.put("token",token);
            jsonModel.setData(userinfo);
            return jsonModel;
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }

    @Override
    public User selectUserDetailsByUserId(String userid) {
        User user = userMapper.selectUserDetailsByUserId(userid);
        return user;
    }
}
